<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Node;
use http\QueryString;
use Illuminate\Http\Request;

class NodeController extends CommonController
{
    /**
     *节点列表
     */
    public function index(Request $request)
    {
        $name=$request->get('name');
        $data=(new Node())->getAllList();
        //收索
    /*    $data=Node::when($name,function ($query) use ($name){
            //模糊查询
            $query->where('name','like',"%{$name}%");
        })->paginate($this->page);
*/
        return view('admin.node.index',compact('data'));
    }

    /**
     * 添加节点
     */
    public function create()
    {
        $data=Node::where('pid',0)->get();
        return view('admin.node.create',compact('data'));
    }

    /**
     *处理添加
     */
    public function store(Request $request)
    {
        try {
            $post = $this->validate($request, [
                'name' => 'required|unique:nodes,name',
                'pid' => 'required',
                'route_name'=>'unique:nodes,route_name',
                'is_menu' => 'required'
            ]);
            Node::create($post);
            return ['status' => 0, 'msg' => '添加成功'];
        }catch (\Exception $e) {

            return ['status' => 1000, 'msg' => '验证不通过'];
        }
    }

    /**
     * Display the specified resource
     * 根据id显示详情
     */
    public function show(Node $node)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *修改视图
     */
    public function edit(Node $node)
    {
        $data=Node::where('pid','0')->get();
        return view('admin.node.edit',compact('node','data'));
    }

    /**
     * Update the specified resource in storage.
     *修改处理
     */
    public function update(Request $request, Node $node)
    {
        //验证
        $post=$this->validate($request,[
            'name' => 'required|unique:nodes,route_name,' .$node->id,
            'pid' => 'required',
            'route_name'=>'unique:nodes,route_name,'.$node->id ,
            'is_menu' => 'required'
        ]);
        $node->update($post);
        return redirect(route('admin.node.index'))->with(['error'=>'修改成功']);
    }

    /**
     * Remove the specified resource from storage.
     *删除
     */
    public function destroy(Node $node)
    {
        $node->delete();
        return ['status'=>0,'msg'=>'删除成功'];
    }
}
